# - Try to find OpenJPEG
# Once done this will define
#
#  OPENJPEG_FOUND - system has OpenJPEG
#  OPENJPEG_INCLUDE_DIR - The include directory for OpenJPEG headers
#  OPENJPEG_LIBRARIES - Link these to use OpenJPEG
#
# Redistribution and use is allowed according to the terms of the BSD license.
#

if ( OPENJPEG_LIBRARIES )
   # in cache already
   SET(OpenJPEG_FIND_QUIETLY TRUE)
endif ( OPENJPEG_LIBRARIES )

# use pkg-config to get the directories and then use these values
# in the FIND_PATH() and FIND_LIBRARY() calls
if( NOT WIN32 )
  find_package(PkgConfig)

  pkg_check_modules(OPENJPEG_PKG QUIET openjpeg)
endif( NOT WIN32 )


# Find libopenjpeg and associated header files (Required)
FIND_LIBRARY(OPENJPEG_LIBRARIES NAMES openjpeg
  PATHS
    /usr/local
    /usr
  HINTS
    ${OPENJPEG_PKG_LIBRARY_DIRS} # Generated by pkg-config
  PATH_SUFFIXES
    lib64
    lib
)
IF ( NOT(OPENJPEG_LIBRARIES) )
  MESSAGE(STATUS "Could not find OpenJPEG library." )
ENDIF()


FIND_PATH(OPENJPEG_INCLUDE_DIR NAMES openjpeg.h
  PATHS
    /usr/local/include
    /usr/include
  HINTS
    ${OPENJPEG_PKG_INCLUDE_DIRS} # Generated by pkg-config
  PATH_SUFFIXES
    openjpeg-1.4
)
IF ( NOT(OPENJPEG_INCLUDE_DIR) )
  MESSAGE(STATUS "Could not find OpenJPEG headers." )
ENDIF ()

IF ( OPENJPEG_LIBRARIES AND OPENJPEG_INCLUDE_DIR )
  TRY_RUN(
    OPENJPEG_VERSION_RUN
    OPENJPEG_VERSION_COMPILE
    ${CMAKE_BINARY_DIR}/CMakeFiles/CMakeTmp
    ${CMAKE_CURRENT_LIST_DIR}/FindOpenJPEGVersion.c
    CMAKE_FLAGS "-DLINK_LIBRARIES=openjpeg"
    COMPILE_OUTPUT_VARIABLE TMP_OUT
    RUN_OUTPUT_VARIABLE OPENJPEG_VERSION_STRING
  )
ENDIF ()

include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenJPEG REQUIRED_VARS OPENJPEG_LIBRARIES OPENJPEG_INCLUDE_DIR VERSION_VAR OPENJPEG_VERSION_STRING)


# show the OPENJPEG_(XPDF/QT4)_INCLUDE_DIR and OPENJPEG_LIBRARIES variables only in the advanced view
MARK_AS_ADVANCED(OPENJPEG_INCLUDE_DIR OPENJPEG_LIBRARIES)

